package com.mjfeed.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.mjfeed.Constants;
import com.mjfeed.entity.ProductImage;
import com.mjfeed.service.ProductImageService;
import com.mjfeed.util.ImageUtils;

@Service("productImageService")
public class ProductImageServiceImpl implements ProductImageService {
	@Resource(name = "taskExecutor")
	private TaskExecutor taskExecutor;

	public void build(ProductImage productImage) {
		MultipartFile multipartFile = productImage.getFile();
		if (multipartFile != null && !multipartFile.isEmpty()) {
			try {
				String uploadPath = Constants.UPLOAD_PATH_PREFIX_PRODUCTIMAGE + DateFormatUtils.format(new Date(), "yyyyMMdd")+"/";
				String uuid = UUID.randomUUID().toString();
				String sourcePath = uploadPath + uuid + "-source." + FilenameUtils.getExtension(multipartFile.getOriginalFilename());
				String largePath = uploadPath + uuid + "-large." + Constants.DEST_EXTENSION_PRODUCTIMAGE;
				String mediumPath = uploadPath + uuid + "-medium." + Constants.DEST_EXTENSION_PRODUCTIMAGE;
				String thumbnailPath = uploadPath + uuid + "-thumbnail." + Constants.DEST_EXTENSION_PRODUCTIMAGE;

				File tempFile = new File(System.getProperty("java.io.tmpdir") + "/upload_" + UUID.randomUUID() + ".tmp");
				if (!tempFile.getParentFile().exists()) {
					tempFile.getParentFile().mkdirs();
				}
				multipartFile.transferTo(tempFile);
				addTask(sourcePath, largePath, mediumPath, thumbnailPath, tempFile, multipartFile.getContentType());
				productImage.setSource(sourcePath);
				productImage.setLarge(largePath);
				productImage.setMedium(mediumPath);
				productImage.setThumbnail(thumbnailPath);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 添加图片处理任务
	 * 
	 * @param sourcePath
	 *            原图片上传路径
	 * @param largePath
	 *            图片文件(大)上传路径
	 * @param mediumPath
	 *            图片文件(小)上传路径
	 * @param thumbnailPath
	 *            图片文件(缩略)上传路径
	 * @param tempFile
	 *            原临时文件
	 * @param contentType
	 *            原文件类型
	 */
	private void addTask(final String sourcePath, final String largePath, final String mediumPath, final String thumbnailPath, final File tempFile, final String contentType) {
		try {
			taskExecutor.execute(new Runnable() {
				public void run() {
					String tempPath = System.getProperty("java.io.tmpdir");
					File largeTempFile = new File(tempPath + "/upload_" + UUID.randomUUID() + "." + Constants.DEST_EXTENSION_PRODUCTIMAGE);
					File mediumTempFile = new File(tempPath + "/upload_" + UUID.randomUUID() + "." + Constants.DEST_EXTENSION_PRODUCTIMAGE);
					File thumbnailTempFile = new File(tempPath + "/upload_" + UUID.randomUUID() + "." + Constants.DEST_EXTENSION_PRODUCTIMAGE);
					try {
						ImageUtils.zoom(tempFile, largeTempFile, 800, 800);
						ImageUtils.zoom(tempFile, mediumTempFile, 300, 300);
						ImageUtils.zoom(tempFile, thumbnailTempFile, 170, 170);
						upload(sourcePath, tempFile, contentType);
						upload(largePath, largeTempFile, Constants.DEST_CONTENT_TYPE_PRODUCTIMAGE);
						upload(mediumPath, mediumTempFile, Constants.DEST_CONTENT_TYPE_PRODUCTIMAGE);
						upload(thumbnailPath, thumbnailTempFile, Constants.DEST_CONTENT_TYPE_PRODUCTIMAGE);
					} finally {
						FileUtils.deleteQuietly(tempFile);
						FileUtils.deleteQuietly(largeTempFile);
						FileUtils.deleteQuietly(mediumTempFile);
						FileUtils.deleteQuietly(thumbnailTempFile);
					}
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void upload(String path, File file, String contentType) {
		File destFile = new File(path);
		try {
			FileUtils.moveFile(file, destFile);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
